<template>
    <div>
        <div class="form-container sign-in-container">
            <div class="overlay">

                <div class="overlay-panel overlay-right">
                    <img style="color: aqua;height: 80px;" :src="logoSvg" alt="" />
                    <p>智能数据采集与自动控制系统</p>

                </div>
            </div>
        </div>
        <div class="overlay-container">
            <el-form>
                <h1 style="margin-bottom: 20px;">登录</h1>
                <div class="phone-input-wrapper">
                    <div class="country-code">+86</div>
                    <input type="text" placeholder="请输入手机号码" v-model="phoneNumber" class="phone-input" />
                </div>
                <div class="phone-input-wrapper" style="background-color: #ffffff;">
                    <input style="border-radius: 8px;background-color: #eeeeee;" type="text" placeholder="请输入数字"
                        v-model="code" class="phone-input" />
                    <div v-html="captchaData" @click="() => {
                        initCaptcha()
                    }"></div>
                </div>

                <div class="code-input-wrapper">
                    <input type="text" placeholder="请输入验证码" v-model="verificationCode" class="code-input" />
                    <button type="button" class="send-code-button" @click="sendVerificationCode" :disabled="isSending">
                        {{ buttonLabel }}
                    </button>
                </div>
                <div v-if="showAlert" class="alert-message-wrapper">

                    <span class="alert-text">验证码已发送到你的手机，15分钟内输入有效，验证码等同于密码，请不要轻易告知他人</span>
                </div>
                <button style="margin-top: 30px;" type="button" @click="login" class="submit-button">立即登录</button>
                <div v-if="loginError" style="color: red;font-size: small;" class="alert-message-wrapper">
                    {{ loginError }}
                </div>

            </el-form>
        </div>
    </div>
</template>

<script setup>
import logoSvg from '@/assets/img/Logo.svg'
import { ref, getCurrentInstance, onMounted } from 'vue'
import { useRouter } from 'vue-router';
const router = useRouter();
import { userInfo } from '@/utils/auth';

const props = defineProps({
    routerTo: String,
});
const emit = defineEmits(['afterLogin']);
const { proxy } = getCurrentInstance(); // 获取当前实例以访问全局属性



const phoneNumber = ref('');
const verificationCode = ref('');
const isSending = ref(false);
const buttonLabel = ref('发送验证码');
const showAlert = ref(false);
const loginError = ref('');
const phoneNumberError = ref(false);
const verificationCodeError = ref(false);
let countdown = 60;
let interval = null;

const code = ref('')
const captchaId = ref('')
const captchaData = ref('')

onMounted(() => {
    // 初始化验证码
    initCaptcha()
})

const initCaptcha = async () => {
    const response = await proxy.$axios.get('/app/user/login/captcha', {
        params: {
            type: "svg", color: "#000000"
        }
    })
    captchaId.value = response.data.data.captchaId
    captchaData.value = response.data.data.data
}



const sendVerificationCode = async () => {
    phoneNumberError.value = false;
    if (!phoneNumber.value) {
        phoneNumberError.value = true;
        ElMessage({
            message: '请输入正确的手机号码',
            type: 'error',
        });
        return;
    }

    try {

        const response = await proxy.$axios.post('/app/user/login/smsCode', {
            phone: phoneNumber.value,
            captchaId: captchaId.value,
            code: code.value
        });
        console.log(response)
        if (response.data.code === 1001) {
            ElMessage({
                message: response.data.message,
                type: 'error',
            });
            return
        }

        // 显示成功提示
        ElMessage({
            message: '验证码发送成功',
            type: 'success',
        });

        showAlert.value = true;

        isSending.value = true;
        buttonLabel.value = `${countdown}s`;

        interval = setInterval(() => {
            countdown -= 1;
            if (countdown > 0) {
                buttonLabel.value = `${countdown}s`;
            } else {
                clearInterval(interval);
                isSending.value = false;
                buttonLabel.value = '发送验证码';
                countdown = 60;
            }
        }, 1000);
    } catch (error) {
        // 显示错误提示
        ElMessage({
            message: '验证码发送失败，请稍后重试',
            type: 'error',
        });
    }
};

const afterLogin = () => {
    if (props.routerTo === '/') {
        router.push('/');
    } else {
        emit('afterLogin')
    }
};

const login = async () => {
    loginError.value = '';
    phoneNumberError.value = false;
    verificationCodeError.value = false;

    if (!phoneNumber.value || !verificationCode.value) {
        phoneNumberError.value = true;
        ElMessage({
            message: '请正确填写信息',
            type: 'error',
        });
        return;
    }

    try {
        const response = await proxy.$axios.post('/app/user/login/phone', {
            phone: phoneNumber.value,
            smsCode: verificationCode.value,
        });

        const { token, refreshToken, expire, refreshExpire } = response.data.data;

        // 计算 token 和 refreshToken 的过期时间
        const expireTime = Date.now() + expire * 1000;
        const refreshExpireTime = Date.now() + refreshExpire * 1000;

        // 存储 token 和 refreshToken 以及它们的过期时间
        localStorage.setItem('token', token);
        localStorage.setItem('refreshToken', refreshToken);
        localStorage.setItem('tokenExpireTime', expireTime);
        localStorage.setItem('refreshTokenExpireTime', refreshExpireTime);

        // 获取用户信息
        const userResponse = await proxy.$axios.get('/app/user/info/person', {
            headers: {
                Authorization: `${token}`,
            },
        });
        userInfo.value = userResponse.data.data;

        ElMessage({
            message: '登录成功',
            type: 'success',
        });

        afterLogin();

    } catch (error) {
        ElMessage({
            message: '登录失败，请检查您的手机号和验证码',
            type: 'error',
        });
        loginError.value = '登录失败，请检查您的手机号和验证码';
    }

};
</script>

<style src="./loginBox.css" scoped></style>

<style scoped>
.send-code-button:hover {
    background-color: #50e1c0 !important;
}

.submit-button:hover {
    background-color: #74e7ac;
}
</style>